<template>
  <view>
    <view class="settle-container">
      <view class="left">
        <label class="radio" @click="changeAllState">
          <radio color="red" :checked="isFullCheck"></radio>
        </label>
        <text>全选</text>
      </view>
      <view class="mid">
        合计: <text class="price">¥{{checkedGoodsAmount}}</text>
      </view>
      <view class="right">
        <view class="btn-settle" @click="settlement">
          结算({{checkedCount}})
        </view>
      </view>
    </view>

  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex'
  export default {
    name: "my-settle",
    data() {
      return {
        seconds: 3,
        timer: null
      };

    },
    computed: {
      ...mapState('m_cart', ['cart']),
      ...mapState('muser', ['token', 'address']),
      ...mapGetters('m_cart', ['checkedCount', 'total', 'checkedGoodsAmount']),
      ...mapGetters('muser', ['addstr']),
      // 2. 是否全选
      isFullCheck() {
        return this.total === this.checkedCount
      },
    },
    methods: {
      ...mapMutations('muser', ['updateRedirectInfo']),
      ...mapMutations('m_cart', ['updateAllGoodsState']),
      //label上的处理函数
      changeAllState() {
        // 修改购物车中所有商品的选中状态
        // !this.isFullCheck 表示：当前全选按钮的状态取反之后，就是最新的勾选状态
        this.updateAllGoodsState(!this.isFullCheck)
      },
      settlement() {
        // 1. 先判断是否勾选了要结算的商品
        if (!this.checkedCount) return uni.$showMsg('请选择要结算的商品！')
        // 2. 再判断用户是否选择了收货地址
        if (!this.address) return uni.$showMsg('请选择收货地址！')
        // 3. 最后判断用户是否登录了，如果没有登录，则调用 delayNavigate() 进行倒计时的导航跳转
        if (!this.token) return this.delayNavigate()
        // 4.实现微信支付功能
        this.payOrder()
      },
     async payOrder() {
        // 创建订单
        const orderInfo = {
          order_price: this.checkedGoodsAmount, //结算总额
          consignee_addr: this.addstr,
          goods:this.cart.filter(e=>e.goods_state).map(e=>({goods_id: e.goods_id, goods_number: e.goods_count, goods_price: e.goods_price }))
        }
        //请求创建订单
        const {data:res} = await uni.$http.post('/api/public/v1/my/orders/create',orderInfo)
         if (res.meta.status !== 200) return uni.$showMsg('创建订单失败！')
         const orderNumber = res.message.order_number
         //订单预支付
         const {data:res2} = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', { order_number: orderNumber })
         if (res2.meta.status !== 200) return uni.$showError('预付订单生成失败！')
           // 2.3 得到订单支付相关的必要参数
           const payInfo = res2.message.pay
           //发起微信支付
           const [err,succ] = await uni.requestPayment(payInfo)
           if (err) return uni.$showMsg('订单未支付！')
           const {data:res3} = await uni.$http.post('/api/public/v1/my/orders/chkOrder', { order_number: orderNumber })
           if (res3.meta.status !== 200) return uni.$showMsg('订单未支付！')
           //成功提示
             uni.showToast({
                title: '支付完成！',
                icon: 'success'
              })
      },
      //启动倒计时
      delayNavigate() {
        this.seconds = 3
        this.showTips(this.seconds)
        // 创建定时器，每隔 1 秒执行一次
        this.timer = setInterval(() => {
          //秒数自减 1
          this.seconds--
          if (this.seconds <= 0) {
            clearInterval(this.timer)
            // 页面跳转
            uni.switchTab({
              url: '/pages/my/my',
              success: () => {
                // 调用 vuex 的 updateRedirectInfo 方法，把跳转信息存储到 Store 中
                this.updateRedirectInfo({
                  // 跳转的方式
                  openType: 'switchTab',
                  // 从哪个页面跳转过去的
                  from: '/pages/cart/cart'
                })
              },
            })
            return
          }
          // 再根据最新的秒数，进行消息提示
          this.showTips(this.seconds)
        }, 1000)
      },
      showTips(n) {
        //展示提示信息
        uni.showToast({
          icon: 'none',
          title: '请登录后再结算!' + n + '秒后跳转至登录页面',
          //添加透明遮罩
          mask: true,
          // 消失时间
          duration: 1500
        })
      }
    }
  }
</script>

<style lang="scss">
  .settle-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 5px;
    font-size: 14px;
    border-top: 1px solid #efefef;

    .left {
      display: flex;
      align-items: center;
    }

    .mid {
      .price {
        font-size: 16px;
        color: #c00000;
      }
    }

    .right {
      .btn-settle {
        min-width: 100px;
        line-height: 50px;
        text-align: center;
        background-color: #c00000;
        font-size: 18px;
        color: #fff;
      }
    }
  }
</style>
